package com.qf.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.consants.RabbitMQConstants;
import com.qf.entity.Goods;
import com.qf.shopsearch.ShopSearchApplication;
import com.rabbitmq.client.Channel;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class GoodsQueueEsListener {

    @Value("${es.index}")
    private String index;

    @Value("${es.type}")
    private String type;

    @Autowired
    private RestHighLevelClient client;

    // 创建一个固定长度的线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(5);

    // 指定该方法监听的队列
    @RabbitListener(queues = RabbitMQConstants.GOODS_QUEUE_ES)
    public void insertEs(Goods goods, Channel channel, Message message) {

        "xxxx".hashCode();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    IndexRequest request = new IndexRequest(index, type);
                    request.source(objectMapper.writeValueAsString(goods), XContentType.JSON);
                    IndexResponse index = client.index(request, RequestOptions.DEFAULT);

                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
